/* 
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

Project: MyMANET - A Platform to Build Customized MANET's
Developers: Ashwin Paranjpe, Santosh Vempala
Georgia Institute of Technology, Atlanta, USA
*/

#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

#define BUFFER_LEN 512
#define NUM_OF_PACKETS 40
#define PORT 9931

int main(int argc, char **argv)
{
	struct sockaddr_in si_other;
	int s, slen=sizeof(si_other);
	char buf[BUFFER_LEN];
	char file_name[60];
	int i=0, num_of_files=0;
     
	if(argc != 2){
		printf("\nUsage: ./fclient [SERVER_IP]\n");
		exit(1);
	}	

	if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1){
		perror("socket");
		exit(1);
    	}

	memset((char *) &si_other, 0, sizeof(si_other));
	si_other.sin_family = AF_INET;
	si_other.sin_port = htons(PORT);

	if ((inet_aton(argv[1], &si_other.sin_addr)) == 0) {
		fprintf(stderr, "inet_aton() failed\n");
		exit(1);
	}
    
	while(1){
		char command[60]="";

		printf("\nEnter the name of the file you want to fetch from Server %s: ", argv[1]);
		gets(file_name);
		sprintf(buf, "%s", file_name);

		if (sendto(s, buf, BUFFER_LEN, 0, (struct sockaddr *)&si_other, slen)==-1){
			perror("sendto()");
			exit(1);
		}

		memset(buf, 0, BUFFER_LEN);
		printf("Waiting for response from Server");
		if (recvfrom(s, buf, BUFFER_LEN, 0, (struct sockaddr *)&si_other, (int *)&slen)==-1){
			perror("recvfrom:");
			exit(1);
		}
		printf("\nMsg from Server: %s\n", buf);
		num_of_files = atoi(buf);
		i=0;
		char c = '0';
		char d = '0';
		while(i < num_of_files){
			sprintf(command, "./expect_code_get.exp %s %s%c%c", argv[1], file_name, c, d);
			system(command);
			memset(command, 0, sizeof(command));
			d = d + 1;
			int x = ((d - '0')%10); 
			if(x == 0){
				c = c + 1;
				d = '0';
			}
			else{
			}
			i++;
		}

	}
    
	close(s);
	return 0;
}

